/*
 * @Descripttion:
 * @Author: jhw
 * @Date: 2024-04-25 09:53:04
 * @LastEditors: jhw
 * @LastEditTime: 2024-04-26 11:46:14
 */
/**
 * @description 判断是否是同一个节点
 */
export function sameVnode(oldVnode, newVnode) {
  return oldVnode.sel === newVnode.sel && oldVnode.key === newVnode.key;
}

/**
 * @description 创建真实DOM
 */
export function createElement(vnode) {
  const domNode = document.createElement(vnode.sel);
  vnode.elm = domNode;
  // 判断是否有子元素
  if (
    vnode.text !== undefined &&
    (vnode.children === undefined || vnode.children.length === 0)
  ) {
    domNode.innerText = vnode.text;
    // 将data中所有属性挂载到真实DOM上
    if (vnode.data !== undefined) {
      for (let key in vnode.data) {
        if (key === "props") {
          for (let propKey in vnode.data.props) {
            domNode[propKey] = vnode.data.props[propKey];
          }
        } else if (key === "style") {
          for (let styleKey in vnode.data.style) {
            domNode.style[styleKey] = vnode.data.style[styleKey];
          }
        }
        // 其他属性xxx源码几乎都有
      }
    }
  } else if (Array.isArray(vnode.children) && vnode.children.length > 0) {
    vnode.children.forEach((child) => {
      const childNode = createElement(child);
      domNode.appendChild(childNode);
    });
  }
  return vnode.elm;
}

/**
 * @description 创建key-index映射表
 */
export function createKeyToIndex(children, beginIdx, endIdx) {
  const map = {};
  for (let i = beginIdx; i <= endIdx; i++) {
    const key = children[i].key;
    if (key !== undefined) {
      map[key] = i;
    }
  }
  return map;
}
